#ifndef TESTCOMBOBOX_H
#define TESTCOMBOBOX_H

#include <QWidget>
#include<QStandardItemModel>
#include<QComboBox>
#include<QDebug>

class TestComboBox : public QWidget
{
    Q_OBJECT
public:
    explicit TestComboBox(QWidget *parent = nullptr);

signals:

};

class CustomComboModel : public QStandardItemModel
{
    Q_OBJECT
public:
    explicit CustomComboModel(QObject *parent = nullptr) : QStandardItemModel(parent) {}

    QVariant data(const QModelIndex &index, int role) const override {
        if (role == Qt::ForegroundRole && index.row() == 0) {
            return QColor(Qt::red); // 第一项显示为红色
        }
        return QStandardItemModel::data(index, role);
    }
};

class CustomComboPopup : public QWidget
{
    Q_OBJECT
public:
    explicit CustomComboPopup(QWidget *parent = nullptr);

signals:
     void selected(const QString &text);
};

class CustomComboBox2 : public QComboBox {
    Q_OBJECT
public:
    CustomComboBox2(QWidget *parent = nullptr) : QComboBox(parent) {
        popup = new CustomComboPopup(this);
        connect(popup, &CustomComboPopup::selected, this, [this](const QString &text) {
            if (!text.isEmpty()) {
                qDebug()<<"selected text";
                clear();

                // 添加新的文本项

                addItem(text);

                // 设置当前索引为新添加的项（即第0项，因为clear后只添加了一项）

                setCurrentIndex(0);
                //setCurrentText(text);

            }
        });
    }

protected:
    void showPopup() override {
        //QPoint pos = mapToGlobal(QPoint(0, height()));
        //popup->move(pos);
        //popup->resize(width(), 150); // 设置弹出窗口大小

        // 计算弹出位置（在组合框下方）
        QPoint pos = mapToGlobal(QPoint(0, height()));

        // 移动弹出窗口到正确位置
        popup->move(pos);

        // 设置弹出窗口宽度与组合框相同，高度自适应
        popup->resize(width(), popup->sizeHint().height());

        popup->show();
    }
    void hidePopup() override {
        // 隐藏弹出窗口
        if (popup && popup->isVisible()) {
            popup->hide();
        }
    }

private:
    CustomComboPopup *popup;
};

#endif // TESTCOMBOBOX_H
